package com.likai.index;

import com.likai.dao.IJarMapper;
import com.likai.pojo.JarBean;
import com.likai.util.SqlSessionFactoryUtil;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * Created by likai on 2018/10/13.
 * 生成jar包索引
 */
public class JarsIndex {

    //获取日志对象
    private static Logger logger = Logger.getLogger(JarsIndex.class) ;

    public static void main(String [] args) {
        logger.info("创建索引开始");

        //实例化sqlSession
        SqlSession sqlSession = SqlSessionFactoryUtil.openSqlSession() ;
        //实例化接口jarMapper
        IJarMapper jarMapper = sqlSession.getMapper(IJarMapper.class) ;


        try {
            //写索引目录
            Directory dir =  FSDirectory.open(Paths.get("D:" + File.separator + "lucene")) ;

            //实例化标准分词器(根据空格)
            Analyzer analyzer = new StandardAnalyzer() ;

            IndexWriterConfig config = new IndexWriterConfig(analyzer) ;

            //创建写索引
            IndexWriter writer = new IndexWriter(dir,config) ;

            //获取数据库中indexState=0的数据
            List<JarBean> jarList = jarMapper.selectInfoByIndexState() ;
            for (JarBean jarBean : jarList) {
                String uuid = jarBean.getUuid() ;
                String name = jarBean.getName() ;
                Document document = new Document() ;
                //StringField不进行分词
                document.add(new StringField("id",uuid, Field.Store.YES));
                //将-替换为空格进行分词
                document.add(new TextField("name",name.replaceAll("-"," "),Field.Store.YES));
                //写入文档
                writer.addDocument(document);

                //更新数据indexState改为1
                jarBean.setIndexState(1);
                jarMapper.updateDynamic(jarBean) ;
                sqlSession.commit();
            }
            //如果不关闭创建的索引将会出现异常
            writer.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

        try{
            sqlSession.close();

        } catch (Exception e) {
            logger.error("Exception",e);
        }

        logger.info("创建索引完成");
    }
}
